package com.sky.controller.user;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
@Api(tags = "c端地址接口")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    @PostMapping()
    public Result<String> addAddress(@RequestBody AddressBook addressBook)
    {
        log.info("添加地址{}",addressBook);
        addressBookService.addAddress(addressBook);
        return Result.success();
    }
    @GetMapping("/list")
    public Result<List<AddressBook>> list()
    {
        log.info("查询当前用户所有地址");
        AddressBook addressBook =new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBookList=addressBookService.list(addressBook);
        return Result.success(addressBookList);
    }
    @GetMapping("/{id}")
    public Result<AddressBook> getAddress(@PathVariable Long id)
    {
        log.info("根据id查询当前的地址{}",id);
        AddressBook addressBook=addressBookService.getAddressByid(id);
        return Result.success(addressBook);
    }
    @PutMapping
    public Result upadte (@RequestBody AddressBook addressBook)
    {
        log.info("修改地址");
        addressBookService.update(addressBook);
        return  Result.success();
    }
    @PutMapping("/default")
    public  Result setDefault(@RequestBody AddressBook addressBook)
    {
        log.info("设置默认地址{}",addressBook);
        addressBookService.setDefault(addressBook);
        return  Result.success();
    }
    @DeleteMapping()
    public Result deleteByid(Long id)
    {
        addressBookService.deleteByid(id);
        return Result.success();
    }
    @GetMapping("/default")
    public Result<AddressBook> getDefault()
    {
        AddressBook addressBook =new AddressBook();
        addressBook.setIsDefault(1);
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> addressBookList = addressBookService.list(addressBook);
        if (addressBookList!=null&&addressBookList.size()==1){
            return  Result.success(addressBookList.get(0));
        }
        return Result.error("没有查询默认地址");
    }


}
